package utils

import (
	"bytes"
	"fmt"
	"github.com/xuri/excelize/v2"
	"gorm.io/gorm/schema"
	"reflect"
)

//tag 的 定义 excel:"name:?;place:?"

func CreateExcelTest(T []any) (*bytes.Buffer, error) {
	//长度暂时定为26，后面可以继续加
	// var excelIndex = []string{"A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"}
	m, err := GetExcelNameByStruct1(T[0])
	if err != nil {
		return nil, err
	}
	// var i = 0
	f := excelize.NewFile()
	defer func() {
		if err := f.Close(); err != nil {
			fmt.Println(err)
		}
	}()
	// 遍历 Map
	for _, v := range m {
		f.SetCellValue("Sheet1", v["PLACE"]+"1", v["NAME"])
	}

	var k = 2
	for _, value := range T {

		typ := reflect.TypeOf(value)
		val := reflect.ValueOf(value)
		num := val.NumField()
		for j := 0; j < num; j++ {
			name := typ.Field(j).Name
			valueExcel := val.Field(j)
			excelRow := m[name]["PLACE"]
			s := fmt.Sprintf("%s%d", excelRow, k)
			f.SetCellValue("Sheet1", s, valueExcel)
		}
		k++

	}

	data, _ := f.WriteToBuffer()
	return data, nil
}

func GetExcelNameByStruct1(a interface{}) (map[string]map[string]string, error) {
	m := make(map[string]map[string]string)
	typ := reflect.TypeOf(a)
	val := reflect.ValueOf(a) //获取reflect.Type类型
	kd := val.Kind()          //获取到a对应的类别
	if kd != reflect.Struct {
		fmt.Println("expect struct")
		return m, nil
	}
	//获取到该结构体有几个字段
	num := val.NumField()
	//fmt.Printf("该结构体有%d个字段\n", num) //4个

	//遍历结构体的所有字段
	for i := 0; i < num; i++ {
		//fmt.Printf("Field %v\n", typ.Field(i).Name)
		//获取到struct标签，需要通过reflect.Type来获取tag标签的值
		tagVal := typ.Field(i).Tag.Get("excel")
		excelInfo := schema.ParseTagSetting(tagVal, ";")
		//如果该字段有tag标签就显示，否则就不显示
		if tagVal != "" {
			//fmt.Printf("Field %v:tag=%v\n", typ.Field(i).Name, tagVal)
			m[typ.Field(i).Name] = excelInfo
		}
	}

	return m, nil

}
